package com.sinopec.pi.scalaguide.errorhandle

import java.io.{FileNotFoundException, FileReader, IOException}
import java.net.{MalformedURLException, URL}
import scala.io.Source
import scala.util.{Failure, Success, Try}

object TryCatch {

    // 函数如果可能会抛出异常，则返回 Try
    private def parseURL(url: String): Try[URL] = Try(new URL(url))

    private def getURLContent(url: String): Try[Iterator[String]] = {
        for {
            url <- parseURL(url)
            connection <- Try(url.openConnection())
            is <- Try(connection.getInputStream)
            source = Source.fromInputStream(is)
        } yield source.getLines()
    }

    def main(args: Array[String]): Unit = {
        // 基本的异常处理
        try {
            val t = new FileReader("input.txt")
            t.read()
        }   catch {
            case x: FileNotFoundException => {
                println("Exception: File missing")
            }
            case x: IOException => {
                println("Input/output Exception")
            }
        } finally {
            println("Finally block")
        }

        val triedUrl = parseURL("not valid")

        val url = triedUrl getOrElse new URL("http://duckduckgo.com")
        println(url)

        // 模式匹配处理
        triedUrl match {
            case Success(url) => println(url)
            case Failure(ex) =>  println(s"Problem rendering URL content: ${ex.getMessage}")
        }

        // 从故障中恢复，如果 getURLContent 抛出异常，则对异常进行匹配，返回相应的内容
        val content = getURLContent("garbage") recover {
            case e: FileNotFoundException => Iterator("Requested page does not exist")
            case e: MalformedURLException => Iterator("Please make sure to enter a valid URL")
            case _ => Iterator("An unexpected error has occurred. We are so sorry!")
        }
        println(content)
    }
}
